﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using WmsApp.Lookup;
using WmsApp.Service;
using WmsApp.Style;
using WmsApp.UI;
using WmsApp.Window;
using WmsApp.WmsService;

namespace WmsApp.WindowControl
{
    public class PayApplyBillController
    {
        private ControlType _controlType = ControlType.None;
        private PayApplyBillWrap _wrap = null;
        private PayApplyBillWrap Wrap {
            get { return _wrap; }
            set
            {
                this._wrap = value;
                if(value != null)
                {
                    CmdEnable(true);
                }
            }
        }
        private PayApplyBillCtl payApplyBillCtl = null;
        public PayApplyBillController(PayApplyBillCtl ctl )
        {
            try
            {
                payApplyBillCtl = ctl;
                LookupBind.BindingLookUpEditProvider2(this.payApplyBillCtl.lookUpEditProvider3, this.payApplyBillCtl.textEditProviderName3
                    , this.payApplyBillCtl.textEditOpeningBank3, this.payApplyBillCtl.textEditBankAccount3);
                LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditChargeID3, this.payApplyBillCtl.textEditChargeName3, "ChargeName");
                LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditManagerID3, this.payApplyBillCtl.textEditManagerName3, "ManagerName");
                LookupBind.BindingLookUpEditSystemUser(this.payApplyBillCtl.lookUpEditOperatorID3, this.payApplyBillCtl.textEditOperatorName3, "OperatorName");
                LookupBind.BindingLookUpEditPayType(this.payApplyBillCtl.lookUpEditPayTypeCode3, this.payApplyBillCtl.textEditPayTypeName3);

                //LookupBind.BindingLookUpEditIsAlive(this.payApplyBillCtl.gridView3, this.payApplyBillCtl.gridView3.Columns.ColumnByFieldName("ISVALID"));

                this.payApplyBillCtl.gridView3.CellValueChanged += GridView3CellValueChanged;

                CmdEnable(false);
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        private void CmdEnable(bool b)
        {
            this.payApplyBillCtl.CmdSave3.Enabled = b;
            this.payApplyBillCtl.CmdNewDtl3.Enabled = b;
            this.payApplyBillCtl.CmdInAffirm3.Enabled = b;
            this.payApplyBillCtl.CmdDelete.Enabled = b;

            this.payApplyBillCtl.memoEditQualityFeedback3.Enabled = b;
            this.payApplyBillCtl.memoEditProjectBelong3.Enabled = b;
            this.payApplyBillCtl.memoEditArrivalNotice3.Enabled = b;
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.Enabled = b;
            this.payApplyBillCtl.dateEditPayApplyDate3.Enabled = b;
            this.payApplyBillCtl.lookUpEditPayTypeCode3.Enabled = b;
            this.payApplyBillCtl.lookUpEditOperatorID3.Enabled = b;
            this.payApplyBillCtl.lookUpEditManagerID3.Enabled = b;
            this.payApplyBillCtl.lookUpEditChargeID3.Enabled = b;
            this.payApplyBillCtl.lookUpEditProvider3.Enabled = b;

            this.payApplyBillCtl.textEditOpeningBank3.Enabled = b;
            this.payApplyBillCtl.textEditBankAccount3.Enabled = b;

            this.payApplyBillCtl.dateEditPayApplyInvoiceDate.Enabled = b;
            this.payApplyBillCtl.textEditPayApplyInvoiceNoList.Enabled = b;
        }
        

        private void GridView3CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column == payApplyBillCtl.gridView3.Columns.ColumnByFieldName("ISVALID")
                || e.Column == payApplyBillCtl.gridView3.Columns.ColumnByFieldName("Amount"))
            {
                decimal totalMoney = 0;
                foreach (var applyBillDtl in Wrap.FPayApplyBillDtl)
                {
                    if(applyBillDtl.ISVALID == Constant.IsValidTrue)
                    {
                        totalMoney += applyBillDtl.Amount;
                    }
                }
                Wrap.FPayApplyBill.TotalAmount = totalMoney;
            }
        }

        public string CurrentPayApplyBillID
        {
            get
            {
                if (this.Wrap == null)
                    return String.Empty;
                return this.Wrap.FPayApplyBill.PayApplyBillID;
            }
        }

        public decimal?  CurrentPayApplyBillTotalAmount
        {
            get
            {
                if (this.Wrap == null)
                    return -1;
                return this.Wrap.FPayApplyBill.TotalAmount;
            }
        }

        public string PayApplyState
        {
            get { return Wrap.FPayApplyBill.PayApplyState; }
        }

        public void NewOrLoadPayApplyBill(string payApplyBillID)
        {
            try
            {
                var service = EntityServiceFactory.GetWrapService<PayApplyBillWrap, PayApplyBillWrapService>();
                Wrap = service.GetWrap(payApplyBillID);
                if (Wrap == null)
                {
                    NewPayApplyBill(payApplyBillID);
                }
                else
                {
                    LoadPayApplyBillID(payApplyBillID);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        /// <summary>
        /// 加载一个付款申请单
        /// </summary>
        /// <param name="payApplyBillID"></param>
        public void LoadPayApplyBillID(string payApplyBillID)
        {
            try
            {
                var service = EntityServiceFactory.GetWrapService<PayApplyBillWrap, PayApplyBillWrapService>();
                Wrap = service.GetWrap(payApplyBillID);
                _controlType = ControlType.None;
                this.DataBinding();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        private void BindingDept()
        {
            var list = Factory.WmsServiceFactory.GetServiceClient().GetPayApplyBillDepts();
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.Properties.Items.Clear();
            foreach (var dept in list)
            {
                this.payApplyBillCtl.comboBoxEditPayApplyDept3.Properties.Items.Add(dept);
            }
        }

        private void DataBinding()
        {
            BindingDept();
            //
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.DataBindings.Clear();
            this.payApplyBillCtl.comboBoxEditPayApplyDept3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyDept");
            //
            this.payApplyBillCtl.dateEditPayApplyDate3.DataBindings.Clear();
            this.payApplyBillCtl.dateEditPayApplyDate3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyDate");
            //
            this.payApplyBillCtl.lookUpEditChargeID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditChargeID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ChargeID");
            //
            this.payApplyBillCtl.lookUpEditManagerID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditManagerID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ManagerID");
            //
            this.payApplyBillCtl.lookUpEditOperatorID3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditOperatorID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OperatorID");
            //
            this.payApplyBillCtl.lookUpEditPayTypeCode3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditPayTypeCode3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayTypeCode");
            //
            this.payApplyBillCtl.lookUpEditProvider3.DataBindings.Clear();
            this.payApplyBillCtl.lookUpEditProvider3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProviderCode");
            //
            this.payApplyBillCtl.textEditBankAccount3.DataBindings.Clear();
            this.payApplyBillCtl.textEditBankAccount3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "BankAccount");
            //
            this.payApplyBillCtl.textEditBillID3.DataBindings.Clear();
            this.payApplyBillCtl.textEditBillID3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyBillID");
            //
            this.payApplyBillCtl.textEditChargeName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditChargeName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ChargeName");
            //
            this.payApplyBillCtl.textEditIdx3.DataBindings.Clear();
            this.payApplyBillCtl.textEditIdx3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "Idx");
            //
            this.payApplyBillCtl.textEditManagerName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditManagerName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ManagerName");
            //
            this.payApplyBillCtl.textEditOpeningBank3.DataBindings.Clear();
            this.payApplyBillCtl.textEditOpeningBank3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OpeningBank");
            //
            this.payApplyBillCtl.textEditOperatorName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditOperatorName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "OperatorName");
            //
            this.payApplyBillCtl.textEditPayApplyStateDesc3.DataBindings.Clear();
            this.payApplyBillCtl.textEditPayApplyStateDesc3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyStateDesc");
            //
            this.payApplyBillCtl.textEditPayTypeName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditPayTypeName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayTypeName");
            //
            this.payApplyBillCtl.textEditProviderName3.DataBindings.Clear();
            this.payApplyBillCtl.textEditProviderName3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProviderName");

            //
            this.payApplyBillCtl.dateEditPayApplyInvoiceDate.DataBindings.Clear();
            this.payApplyBillCtl.dateEditPayApplyInvoiceDate.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyInvoiceDate",true,DataSourceUpdateMode.OnValidation);
            //
            this.payApplyBillCtl.textEditPayApplyInvoiceNoList.DataBindings.Clear();
            this.payApplyBillCtl.textEditPayApplyInvoiceNoList.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "PayApplyInvoiceNoList");

            //EndPayApplyDate
            this.payApplyBillCtl.dateEditEndPayApplyDate.DataBindings.Clear();
            this.payApplyBillCtl.dateEditEndPayApplyDate.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "EndPayApplyDate", true, DataSourceUpdateMode.OnValidation);
           
            this.payApplyBillCtl.textEditTotalAmount3.EditValueChanged += (sender, e) =>
                                                                              {
                                                                                  try
                                                                                  {
                                                                                      this.payApplyBillCtl.textEditTotalAmountMax3.Text =
                                                                                      (new MoneyToChineseChanger(
                                                                                          decimal.Parse(this.payApplyBillCtl.textEditTotalAmount3.Text))).ToString();
                                                                                  }
                                                                                  catch (Exception)
                                                                                  {
                                                                                  }
                                                                              };

            //
            this.payApplyBillCtl.textEditTotalAmount3.DataBindings.Clear();
            this.payApplyBillCtl.textEditTotalAmount3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "TotalAmount");
            //
            this.payApplyBillCtl.memoEditArrivalNotice3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditArrivalNotice3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ArrivalNotice");
            //
            this.payApplyBillCtl.memoEditProjectBelong3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditProjectBelong3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "ProjectBelong");
            //
            this.payApplyBillCtl.memoEditQualityFeedback3.DataBindings.Clear();
            this.payApplyBillCtl.memoEditQualityFeedback3.DataBindings.Add("EditValue", Wrap.FPayApplyBill, "QualityFeedback");

            this.payApplyBillCtl.gridControlEdit3.DataSource = Wrap.FPayApplyBillDtl;

            this.payApplyBillCtl.gridControlPayItem.DataSource = Wrap.FPayApplyBillItem;
            RowStyleConditionController.AddStyleFormatCondition((GridView)this.payApplyBillCtl.gridControlPayItem.MainView, "ItemState", "[ItemState] == '作废'");

            if(Wrap == null)
            {
                CmdEnable(false);
            }
            else
            {
                if(Wrap.FPayApplyBill.PayApplyState == Constant.BillStateDraft)
                {
                    CmdEnable(true);
                }
                else
                {
                    CmdEnable(false);
                }
                if(Wrap.FPayApplyBill.WcfEntityState == EntityState.Added)
                {
                    this.payApplyBillCtl.lookUpEditProvider3.Enabled = true;
                }
                else
                {
                    this.payApplyBillCtl.lookUpEditProvider3.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 删除发票，要做两件事，第一从明细中删除，第二将发票的付款申请单号码删掉
        /// </summary>
        /// <param name="dtl"></param>
        public void RemovePayApplyBillDtl(PayApplyBillDtl dtl)
        {
            try
            {
                //Wrap.FPayApplyBillDtl.Remove(dtl);
                if (DialogResult.OK == XtraMessageBox.Show("确实要将该发票从付款单中移除吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    this.Save();
                    var obj = (PayApplyBillDtl)this.payApplyBillCtl.gridView3.GetRow(this.payApplyBillCtl.gridView3.FocusedRowHandle);
                    Factory.WmsServiceFactory.GetServiceClient().DeleteInvoiceBillFromPayApplyBill2(Wrap.FPayApplyBill.PayApplyBillID, obj.InvoiceNo);
                    //this.payApplyBillCtl.gridControlEdit3.RefreshDataSource();
                    this.LoadPayApplyBillID(this._wrap.FPayApplyBill.PayApplyBillID);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        public void AddPayApplyBillDtl()
        {
            try
            {
                if (Wrap != null)
                {
                    if (String.IsNullOrEmpty(Wrap.FPayApplyBill.ProviderCode))
                    {
                        XtraMessageBox.Show("请先选择供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (Wrap.FPayApplyBill.PayApplyState != Constant.BillStateDraft)
                    {
                        XtraMessageBox.Show("非草稿状态下不能添加明细！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    var form = new FormInvoiceSelector(Wrap.FPayApplyBill.ProviderCode);
                    form.ShowDialog();
                    if (form.DialogResult == DialogResult.OK)
                    {
                        var list = form.FExtendInvoiceBill;
                        if (list.Count > 0)
                        {
                            if (Wrap.IsNeedSaved())
                            {
                                Save();
                            }
                            Factory.WmsServiceFactory.GetServiceClient().AttachInvoiceBills2PayApplyBill(
                                Wrap.FPayApplyBill.PayApplyBillID, list);
                            this.LoadPayApplyBillID(Wrap.FPayApplyBill.PayApplyBillID);
                            //如果有发票，且
                            if(Wrap.FPayApplyBillDtl.Count>0 && String.IsNullOrEmpty(_wrap.FPayApplyBill.PayApplyInvoiceNoList))
                            {
                                
                            }
                        }
                    }
                    //int idx = 0;
                    //if (Wrap.FPayApplyBillDtl.Count > 0)
                    //{
                    //    idx = Wrap.FPayApplyBillDtl.Select(e => e.Idx).Max();
                    //}
                    //var dtl = PayApplyBillDtl.CreatePayApplyBillDtl(Wrap.FPayApplyBill.PayApplyBillID);
                    //dtl.Idx = idx + 1;
                    //Wrap.FPayApplyBillDtl.Add(dtl);
                    //this.payApplyBillCtl.gridControlEdit3.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        public void NewPayApplyBill(string inBillID)
        {
            try
            {
                if (Wrap != null)
                {
                    if (Wrap.IsNeedSaved())
                    {
                        if (DialogResult.OK == XtraMessageBox.Show(Wrap.FPayApplyBill.PayApplyBillID + "当前付款申请已修改，要保存吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                        {
                            SavePayApplyBill();
                        }
                    }
                }

                //查询入库单，找到可以生成付款申请单的入库单

                string payApplyBillID = inBillID;
                //if(String.IsNullOrEmpty(payApplyBillID))
                //{
                //    var form = new FormInStoreBillSelector();
                //    form.ShowDialog();
                //    if(DialogResult.OK == form.DialogResult)
                //    {
                //        payApplyBillID = form.FInStoreBill.BillID;
                //    }
                //    else
                //    {
                //        return;
                //    }
                //}

                Wrap = new PayApplyBillWrap();
                Wrap.FPayApplyBill = PayApplyBill.CreatePayApplyBill(payApplyBillID);
                Wrap.FPayApplyBillDtl = new List<PayApplyBillDtl>();
                _controlType = ControlType.New;
                this.DataBinding();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        private bool Save()
        {
            if (Wrap != null && Wrap.FPayApplyBill != null)
            {
                if (String.IsNullOrEmpty(Wrap.FPayApplyBill.ProviderCode))
                {
                    XtraMessageBox.Show("请先选择供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            
                //2010-10-30 added by henrik ，现在可以不输入付款类型
                ////lookUpEditPayTypeCode3
                //if (String.IsNullOrEmpty(Wrap.FPayApplyBill.PayTypeCode))
                //{
                //    XtraMessageBox.Show("请先选择付款类型！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return false;
                //}

                //先校验出库单明细
                string msg = string.Empty;
                bool b = ValidatePayApplyBillDtl(out msg);
                if (!b)
                {
                    Exceptions.ExceptionHandler.ShowException(msg);
                    return false;
                }
                if (_wrap.FPayApplyBill.WcfEntityState == EntityState.Added)
                {       
                    //取号
                    string payApplyBillID = Factory.WmsServiceFactory.GetServiceClient().GetPayApplyBillID();
                    Wrap.FPayApplyBill.PayApplyBillID = payApplyBillID;
                }
                IWrapService<PayApplyBillWrap> wrapService =
                                      EntityServiceFactory.GetWrapService<PayApplyBillWrap, PayApplyBillWrapService>();
                wrapService.SaveWrap(Wrap);
              
                _controlType = ControlType.Saved;
            }
            return true;
        }

        private bool ValidatePayApplyBillDtl(out string msg)
        {
            msg = String.Empty;
            var query = from d in Wrap.FPayApplyBillDtl
                        select new
                        {
                            InvoiceNo = d.InvoiceNo
                        };
            if (Wrap.FPayApplyBillDtl.Count > query.Distinct().Count())
            {
                msg = "发票明细中含有重复的发票号码！";
                return false;
            }
            if (Wrap.FPayApplyBillDtl.Any(dtl => dtl.Amount == 0 ))
            {
                msg = "发票明细中的金额为0！";
                return false;
            }
            return true;
        }

        public void SavePayApplyBill()
        {
            try
            {
                if (Save())
                {
                    XtraMessageBox.Show(Wrap.FPayApplyBill.PayApplyBillID + "保存成功！", "提示", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    this.LoadPayApplyBillID(Wrap.FPayApplyBill.PayApplyBillID);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        public void AffirmInStoreBill()
        {
            try
            {
                if (Save())
                {
                    if (DialogResult.OK == XtraMessageBox.Show("确实要确认该付款申请单吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        if (Wrap.FPayApplyBillDtl.Count ==0)
                        {
                            XtraMessageBox.Show("付款申请单至少需要一条发票明细！", "警告", MessageBoxButtons.OK,
                                                MessageBoxIcon.Warning);
                            return;
                        }

                        Factory.WmsServiceFactory.GetServiceClient().AffirmPayApplyBill(
                            Wrap.FPayApplyBill.PayApplyBillID);
                        _controlType = ControlType.Saved;
                        this.LoadPayApplyBillID(Wrap.FPayApplyBill.PayApplyBillID);
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }
    }
}
